package com.cheche.dn.infrastructure.security;

import com.cheche.dn.Result;
import com.cheche.dn.domain.Apis;
import com.cheche.dn.error.ErrorCode;
import com.cheche.dn.utils.JsonUtil;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.filter.GenericFilterBean;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ManagementEndpointAuthenticationFilter extends GenericFilterBean {

    private final static Logger logger = LoggerFactory.getLogger(ManagementEndpointAuthenticationFilter.class);
    public static final String ADMIN_SESSION_KEY = "admin";
    private AuthenticationManager authenticationManager;

    public ManagementEndpointAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }



    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = asHttp(request);
        HttpServletResponse httpResponse = asHttp(response);

        Optional<String> username = Optional.fromNullable(httpRequest.getParameter("X-Auth-Username"));
        Optional<String> password = Optional.fromNullable(httpRequest.getParameter("X-Auth-Password"));

        String resourceURL = new UrlPathHelper().getPathWithinApplication(httpRequest);

        try {
            if (postToAuthenticate(httpRequest, resourceURL)) {
                logger.debug("Trying to authenticate user {} for management endpoint by X-Auth-Username method", username);
                processManagementEndpointUsernamePasswordAuthentication(httpResponse, username, password);
                return;
            }

            logger.debug("ManagementEndpointAuthenticationFilter is passing request down the filter chain");
            addSessionContextToLogging();
            chain.doFilter(request, response);
        } catch (UsernameNotFoundException usernameNotFoundException) {
            SecurityContextHolder.clearContext();
            returnError(httpResponse, ErrorCode.USER_NOT_EXIST);
        } catch (BadCredentialsException badCredentialsException) {
            SecurityContextHolder.clearContext();
            returnError(httpResponse, ErrorCode.PASSWORD_ERROR);
        } catch (AuthenticationException authenticationException) {
            SecurityContextHolder.clearContext();
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
        } catch (AccessDeniedException accessDeniedException) {
            SecurityContextHolder.clearContext();
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
        } finally {
            MDC.remove(ADMIN_SESSION_KEY);
        }
    }

    private void addSessionContextToLogging() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String adminValue = "EMPTY";
        if (authentication != null && !Strings.isNullOrEmpty(authentication.getPrincipal().toString())) {
            adminValue = authentication.getPrincipal().toString();
        }
        MDC.put(ADMIN_SESSION_KEY, adminValue);
    }

    private HttpServletRequest asHttp(ServletRequest request) {
        return (HttpServletRequest) request;
    }

    private HttpServletResponse asHttp(ServletResponse response) {
        return (HttpServletResponse) response;
    }

    private boolean postToAuthenticate(HttpServletRequest httpRequest, String resourcePath) {
        return Apis.AUTHENTICATE_URL.equalsIgnoreCase(resourcePath) && httpRequest.getMethod().equals(HttpMethod.POST.name());
    }

    private void processManagementEndpointUsernamePasswordAuthentication(HttpServletResponse httpResponse, Optional<String> username, Optional<String> password) throws IOException {
        Authentication resultOfAuthentication = tryToAuthenticateWithUsernameAndPassword(username, password);
        SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);
        returnSuccess(httpResponse, resultOfAuthentication);
    }

    private Authentication tryToAuthenticateWithUsernameAndPassword(Optional<String> username, Optional<String> password) {
        BackendAdminUsernamePasswordAuthenticationToken requestAuthentication = new BackendAdminUsernamePasswordAuthenticationToken(username, password);
        return tryToAuthenticate(requestAuthentication);
    }

    private Authentication tryToAuthenticate(Authentication requestAuthentication) {
        Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication);
        if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) {
            throw new InternalAuthenticationServiceException("Unable to authenticate Backend Admin for provided credentials");
        }
        logger.debug("Backend Admin successfully authenticated");
        return responseAuthentication;
    }

    private void returnSuccess(HttpServletResponse httpResponse,
                               Authentication resultOfAuthentication) throws IOException {
        httpResponse.setStatus(HttpServletResponse.SC_OK);
        Object entity = resultOfAuthentication.getPrincipal();
        Result result = Result.success("token", resultOfAuthentication.getDetails().toString()).
                append(entity.getClass().getSimpleName().toLowerCase(), entity);
        returnResult(httpResponse, result);
    }

    private void returnError(HttpServletResponse httpResponse, ErrorCode errorCode) {
        httpResponse.setStatus(HttpServletResponse.SC_OK);
        Result result = Result.error(errorCode);
        if (errorCode.equals(ErrorCode.ERROR)) {
            result = Result.error(errorCode, "Parameter error");
        }
        try {
            returnResult(httpResponse, result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void returnResult(HttpServletResponse httpResponse, Object result) throws IOException {
        String jsonResponse = JsonUtil.toJson(result);
        httpResponse.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        httpResponse.getWriter().print(jsonResponse);
    }
}
